<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Purchase");
$page_title=__("Purchase");
$content_title=__("Purchase");

$r_payment_channel=array('eswallet');
$r_payment_channel_d=array('eswallet'=>__($vars['eswallet_title'])." ".$vars['currency'].number_format($r_user['eswallet'], 2));
$r_package=$vars['r_active_package'];
$r_package=$vars['r_package'];
$r_package_d=$vars['r_active_package_detail'];
$r_package_d=$vars['r_package_detail'];
/*
array_pop($r_package);
array_pop($r_package);
array_pop($r_package);
array_pop($r_package_d);
array_pop($r_package_d);
array_pop($r_package_d);
*/
$td_width=150;

require_once("inc.register_tab.php");

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_uid"]){
 if(!$r_ref=get_user_detail_by_code($post_d['uid'])){
  $ajerrmsg=replace_tag(__("Member ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['uid']));
 //}elseif($post_s['uid'] != $uid && !is_group_matrix_downline_of_which($post_s['uid'], $uid, 'ref') && !is_group_matrix_downline_of_which($post_s['uid'], $uid, 'matrix_upline')){
 // $ajerrmsg=replace_tag(__("Member ID '<%id%>' does not belong to your group."), array("<%id%>"=>$post_h['uid']));
 }else{
  $ajmsg=replace_tag(__("Member ID: <%id%>, Name: <%name%>, Current Rank: <%rank%>"), array("<%id%>"=>$post_h['uid'], "<%name%>"=>$r_ref['username'], "<%rank%>"=>$vars['rank_index_a_d'][$r_ref['rank_a']]));
 }
 $xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);
 print format_xml($xml);
 exit();
}
//#####END AJAX CALL#####

//#####PRODUCT POST#####
if($_POST["__req"]){
	$refno = $post_s['package'];
	$rank_a = $vars['package'][$refno]['rank'];
	
	if(!strlen($post_s["password"])){
		$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Password")))."<br />\n";
	}else{
		$enc_pass=explode(":", $r_user["ewallet_enc_password"]);
		$salt=$enc_pass[1];
		if(md5($post_s["password"].$salt)!=$enc_pass[0]){
			$errmsg.=__("You have entered an invalid Password.")."<br />\n";
		}
	}
	if(!$errmsg){
		if(!$post_s['uid']){
			$errmsg .= __("Please provide a member id.")."<br />";
		}elseif(!$user = get_user_detail_by_code($post_d['uid'])){
			$errmsg .= replace_tag(__("The member with id '<%uid%>' could not be found."), array("<%uid%>"=>strval($post_h['uid'])))."<br />";
		}
	}
	if(!$errmsg){
		if($user['rank_a']>=$rank_a){						
			$errmsg=__("New package cannot lower or equal with member current package")."<br />\n";
		//}elseif($post_s['uid'] != $uid && !is_group_matrix_downline_of_which($post_s['uid'], $uid, 'ref') && !is_group_matrix_downline_of_which($post_s['uid'], $uid, 'matrix_upline')){
		//	$errmsg=replace_tag(__("Member ID '<%id%>' does not belong to your group."), array("<%id%>"=>$post_h['uid']));
		}
	}
	if(!$errmsg){
		$purchase_descr = '';
		$refno = $post_s['package'];
		$qty = 1;
		//$cost = $vars['package'][$refno]['price'] - ($user['rank_a']>0? $vars['rank_index_a_price'][$user['rank_a']] : 0);
		$cost = $vars['package'][$refno]['price'];
		//$total_bv = $total_dp = $total_rp = $vars['package'][$refno]['bv'] - ($user['rank_a']>0? $vars['rank_index_a_bv'][$user['rank_a']] : 0);
		$total_bv = $total_dp = $total_rp = $vars['package'][$refno]['bv'];
		$purchase_descr.=($purchase_descr? ", " : "").$r_package_d[$refno]." x ".$qty;
		$purchased_prods[$refno] = $qty;
		if(!in_array($post_s['package'], $r_package)){
			$errmsg.=__("Please select a package to purchase.")."<br />\n";
		}
		if(!count($purchased_prods)){
			$errmsg.=__("Please select a package to purchase.")."<br />\n";
		}
		if(!$errmsg){						
			$deduct_amount = $cost;			
			if($r_user[$post_s['payment_channel']]<$deduct_amount){
				$errmsg.=replace_tag(__("You do not have sufficient <%title%> to purchase this package."), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($deduct_amount, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment_channel']], 2)))."<br />\n";
			}
		}
	}

	$preview = $confirm = false;
	if(!$errmsg){
		if(!$post_s['__confirm'] && !$post_s['__edit']){
			$preview = true;
		}elseif($post_s['__confirm']){
			$confirm = true;
		}
	}

	if($confirm && !$errmsg){
		$datetime=ndate();
		$rank_a = $vars['package'][$refno]['rank'];
		if(!mysql_query($sql="update $db->users set $post_s[payment_channel]=$post_s[payment_channel]-$deduct_amount where id='$uid' limit 1")){
			$errmsg.=__("We have encountered some error while purchasing the package.")." ".__("You can try again later. If the problem persists, please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
		}else{
			//insert wallet record
			$purchase_descr2="Purchase of $purchase_descr";
			if(!mysql_query($sql="insert into ".$vars["dbi"]["prefix"]."member_$post_s[payment_channel]_record (uid, type, amount, descr, cdate) values ('$uid', 'd', '$deduct_amount', '".AddSlashes("Debited $vars[currency]".number_format($deduct_amount, 2)." for account activation for member id #$post_s[uid] / $purchase_descr2")."', '$datetime')")){
				$critical_error.="Error creating the member ".$vars[$post_s['payment_channel'].'_title']." record when member id #$uid purchase member id #$post_s[uid]. Please manually execute the SQL below to record the transaction:\n\n$sql\n\nError: ".mysql_error()."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_$post_s[payment_channel]_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal -= $deduct_amount;
				@mysql_query("update {$vars["dbi"]["prefix"]}member_$post_s[payment_channel]_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			$user_id = @mysql_result(mysql_query("select id from {$vars["dbi"]["prefix"]}users where code='$post_d[uid]' limit 1"), 0);			
			//update member rank
			if(!mysql_query($sql="update $db->users set rank_a='$rank_a' where id='$user_id' limit 1")){
				$critical_error.="Error while member id #$uid purchase for member id #$post_s[uid], error updating the member rank.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
			}

            $incentive_amount = $vars['package'][$refno]['incentive'];
            $total_bonus = $incentive_amount * 2;
			if(!mysql_query($sql="insert into $db->incentive set uid='$user_id',package='".$r_package_d[$refno]."',counter='0',amount='".$incentive_amount."',total_bonus='".$total_bonus."',cdate='".date('Y-m-d')."'")){
				$critical_error.="Error while member id #$uid purchase for member id #$post_s[uid], error updating the member rank.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
			}elseif(date('Y-m-d')<='2014-11-30'){
				switch($total_bv){
					case 3000:
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP1000 Copper',counter='-1',amount='6.00',total_bonus='2000',cdate='".date('Y-m-d')."'");
						break;
					case 5000:
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP3000 Bronze',counter='-1',amount='25.00',total_bonus='6000',cdate='".date('Y-m-d')."'");
						break;
					case 10000:
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP5000 White Gold',counter='-1',amount='41.66',total_bonus='10000',cdate='".date('Y-m-d')."'");
						break;	
					case 30000:
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP5000 White Gold',counter='-1',amount='41.66',total_bonus='10000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP5000 White Gold',counter='-1',amount='41.66',total_bonus='10000',cdate='".date('Y-m-d')."'");
						break;	
					case 50000:
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						break;	
					case 100000:
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						mysql_query($sql="insert into $db->incentive set uid='$user_id',package='GBP10000 Silver',counter='-1',amount='83.30',total_bonus='20000',cdate='".date('Y-m-d')."'");
						break;	
				}
			}
			
			//insert purchase record
			$first_sale = true;
			$this_rank=$vars['package'][$refno]['rank'];
			$payment_channel = $post_s['payment_channel'] == 'ewallet'? 'e' : 's';
			$sale_refno = $refno = "S" . rand(10000000,99999990);
			if(!mysql_query($sql="insert into $db->purchase (refno, creator, cid, uid, member_sale, stockist_sale, amount, total_bv, total_dp, total_rp, payment_type, collected, first_sale, rank_a, status, cdate, edate) values ('$refno', 'u', '$uid', '$user_id', 'y', 'n', '$cost', '$total_bv', '$total_dp', '$total_rp', '$payment_channel', 'n', 'y', '$this_rank', 'confirmed', '$datetime', '$datetime')")){
				$critical_error.="Error creating the member purchase record when member ID #$uid purchase member id #$post_s[uid]. Please manually execute the SQL below to record the transaction:\n\n$sql\n\nError: ".mysql_error()."\n";
				$pid="0";
			}else{
				$pid=mysql_insert_id();								
				
				//insert sales detail
				foreach($purchased_prods as $refno => $qty){
					$this_cost=$cost;
					$this_bv=$total_bv;
					if(!mysql_query($sql="insert into $db->purchase_detail (slid, refno, title, prod_type, qty, amount, bv, dp, rp, total, total_bv) values ('$pid', '".AddSlashes($refno)."', '".AddSlashes($r_package_d[$refno])."', 'n', '$qty', '$cost', '$total_bv', '$total_dp', '$total_rp', '$this_cost', '$this_bv')")){
						$critical_error.="Error creating the member sales detail when member ID #$uid purchase member id#$post_s[uid]. Please manually execute the SQL below to record the sales detail.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
					}
				}
			}
			
			//insert chip record
			$main_uid = @mysql_result(mysql_query("select main_uid from {$vars["dbi"]["prefix"]}users where id='$user_id' limit 1"), 0);
			if($main_uid==0) $main_uid = $user_id;
			if(!mysql_query($sql="update $db->users set cwallet=cwallet+$deduct_amount where id='$main_uid' limit 1")){
				$critical_error.="Error creating the member ".$vars['cwallet_title']." record when member id# $main_uid purchase member id #$post_s[uid]. Please manually execute the SQL below to record the transaction:\n\n$sql\n\nError: ".mysql_error()."\n";
			}else{
				$purchase_descr2="Purchase of $purchase_descr";
				if(!mysql_query($sql="insert into ".$vars["dbi"]["prefix"]."member_cwallet_record (uid, type, amount, descr, cdate) values ('$main_uid', 'c', '$deduct_amount', '".AddSlashes("Create $vars[currency]".number_format($deduct_amount, 2)." for account activation for member id #$post_s[uid] / $purchase_descr2")."', '$datetime')")){
					$critical_error.="Error creating the member ".$vars[$post_s['payment_channel'].'_title']." record when member id #$main_uid purchase member id#$post_s[uid]. Please manually execute the SQL below to record the transaction:\n\n$sql\n\nError: ".mysql_error()."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_cwallet_record where uid='$main_uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $deduct_amount;
					@mysql_query("update {$vars["dbi"]["prefix"]}member_cwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
		}

		if(!$errmsg){
			$msg=replace_tag(__("Your have successfully purchase for member id <%uid%> with '<%product%>'."), array("<%uid%>"=>strval($post_h['uid']), "<%product%>"=>$purchase_descr))."<br />\n";
			$r_user=get_user_detail_by_id($uid);
			$r_payment_channel_d=array('ewallet'=>__($vars['ewallet_title'])." ".$vars['currency'].number_format($r_user['ewallet'], 2), 'eswallet'=>__($vars['eswallet_title'])." ".$vars['currency'].number_format($r_user['eswallet'], 2));
		}
	}

	if($critical_error){
		$a_sub="$vars[title] - Activation Failure for Member ID #$uid";
		$a_msg="
		<p>Dear admin,</p>
		<p>There was some error(s) while member ID #$uid purchase his/her account. The error is as follow:</p>
		$critical_error";
		email_admin($a_sub, $a_msg, 'e');
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}

$form_fields=array("uid"=>$r_user['code'],"package"=>'',"payment_channel"=>'',"password"=>"");
foreach($form_fields as $field => $default){
	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$field]=!$post_s['__req']? $default : $post_h[$field];
}

$payment_channel_select=build_select($r_payment_channel, $r_payment_channel_d, $dis['payment_channel'], 'payment_channel', $inputbox_style);
$package_select=build_select($r_package, $r_package_d, $dis['package'], 'package', "style='width:100%;'");

$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js,jquery.livequery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
	j('form[@name=activate_form2]').submit(function(){
		var uid = j('#act_uid').text();
		var pack = j('#act_pack').text();
		var cost = j('#act_cost').text();
		var confirm_text = '".AddSlashes(__("Member account with ID#<#uid#> by purchasing:")).":\\n\\n'+pack+'\\n".AddSlashes(("Total Price")).": '+cost+'\\n\\n".AddSlashes(__("Are you sure?"))."';
		confirm_text = confirm_text.replace(/<#uid#>/, uid);
		if(confirm(confirm_text)){
			j('input[@name=submit_btn]').attr('disabled','disabled');
		}else{
			return false;
		}
	});
	
	j('input#check_uid_btn').click(function(){
		j('span#user_text').html('').removeClass('red');
		if(j('input[@name=uid]').val()==''){
			j('span#user_text').html('".AddSlashes(__("Please provide a Member ID!"))."').addClass('red');
		}else{
			j('span#user_text').html('".AddSlashes(__("Checking..."))."');
			j(this).attr('disabled','disabled');
			j.ajax({
				url: '$this_file?aj=1&check_uid=1',
				data: {'uid': j('input[@name=uid]').val()},
				type: 'post',
				dataType: 'xml',
				error: function(){
					j('span#user_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
				},
				success: function(data){
					var mesg='';
					if(j('loggedout', data).text()=='loggedout'){
						mesg='".AddSlashes(__("You have been logged out."))."';
					}else{
						j(data).find('msg').each(function(){
							mesg+=j(this).text()+' ';
						});
					}
					var status=j(data).find('status').text();
					j('span#user_text').html(mesg).addClass(status==1? 'bold' : 'red');
				},
				complete: function(){
					j('input#check_uid_btn').attr('disabled','');
				}
			});
		}
	}); 
});
function goback(){
	q('__edit').value = 1;
	q('__confirm').value = '';
	document.activate_form2.submit();
}
</script>";

//##### PREVIEW #####
if($preview){
	foreach($post_h as $f=>$v){
		$hidden_fields.="<input type='hidden' name=\"$f\" value=\"$v\" />\n";
	}
	$activate="
	<p>".__("Please review the purchase below and when you are confirm, please click the 'Confirm' button to proceed.")."</p>
	<form name='activate_form2' method='post' action='$this_file'>
	<input type='hidden' name='__req' value='1' />
	<input type='hidden' name='__edit' />
	<input type='hidden' name='__confirm' value='1' />
	$hidden_fields
	<p>Please review your particulars and when you are confirm please click the Register button.</p>
	<table class='pbt_table rev'>
		<tr>
			<td width='$td_width'>".__("Member ID").__(":")."</td>
			<td id='act_uid'>$dis[uid], Name: $user[username], Current Rank: {$vars['rank_index_a_d'][$user['rank_a']]}</td>
		</tr>
		<tr>
			<td width='$td_width'>".__("Activation Package").__(":")."</td>
			<td id='act_pack'>{$r_package_d[$dis['package']]}</td>
		</tr>
		<tr>
			<td width='$td_width'>".__("Activation Cost").__(":")."</td>
			<td id='act_cost'>$vars[currency]".number_format($cost, 2)."</td>
		</tr>
		<tr>
			<td width='$td_width'>".__("Payment Channel").__(":")."</td>
			<td>{$r_payment_channel_d[$dis['payment_channel']]}</td>
		</tr>
	</table>
	<table class='pbt_table'>
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' name='back_btn' value=\"".__("Back")."\" onclick=\"goback();\" />
			<input type='submit' name='submit_btn' value=\"".__("Confirm")."\" />
			</td>
		</tr>
	</table>
	</form>";
}else{
//activate form
$activate=($errmsg || $msg? $errmsg.$msg : "").
//"<p>".__("You can activate your account or other member account here.")." ".replace_tag(__("Your current rank is <%rank%>."), array("<%rank%>"=>$r_user['rank_a']>0? __($vars['rank_index_a_d'][$r_user['rank_a']]) : __("none")))."</p>
"
<form name='activate_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' /><br>
<table class='pbt_table'>
	<tr>
		<td width='$td_width'>".__("Member ID").__(":")."</td>
		<td width='350'><input type='text' name='uid' value=\"$dis[uid]\" $inputbox_style /><!--<br /><span id='user_text'></span><input type='button' name='check_uid_btn' id='check_uid_btn' value=\"".__("Check User")."\" />--></td>
	</tr>
	<tr>
		<td width='$td_width'>".__("Activation Package").__(":")."</td>
		<td>$package_select</td>
	</tr>
	<tr>
		<td width='$td_width'>".__("Payment Channel").__(":")."</td>
		<td>$payment_channel_select</td>
	</tr>
	<tr>
		<td width='$td_width'>".__("AuthCode").__(":")."</td>
		<td><input type='password' name='password' value=\"$dis[password]\" $inputbox_style /></td>
	</tr>
	<tr>
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		<input type='submit' name='submit_btn' value=\"".__("Preview")."\" />
		</td>
	</tr>
</table>
</form>";
}

$content="<h2>$page_title</h2>".$activate;
$content=str_replace("<%tab_content%>", $content, $tab);

print format_member_page($content, $this_title, $content_title, $css.$jvscript);
?>